import axiosInstance from '@/utils/http/api';
import {ElMessage} from 'element-plus';
import axios from 'axios';
import {startLoading, stopLoading} from '@/utils/loading';

export function printClick(templateName: any, list: any) {
    const ids = list.map((item: any) => item.id);

    const paramLoop = [];
    let num = 0;
    for (const item of ids) {
        num++;
        paramLoop.push({
            reportlet: templateName,
            search: item,
            pageType: num
        });
    }

    const printurl = '/webroot/decision/view/report';
    const config = {
        printUrl: printurl,
        isPopUp: false,
        data: {
            reportlets: paramLoop,
            fine_digital_signature: ''
        },
        printType: 0,
        ieQuietPrint: true,
        pageType: 0,
        copy: 1
    };

// 假设localStorage中已经存储了'userVO'这个键
    const userVO = JSON.parse(localStorage.getItem('userVO'));
    let printList = null;
    if (userVO && userVO.printerSetting) {
        printList = userVO.printerSetting;
    }


    const apiPost = import.meta.env.VITE_API_PROXY_TARGET;
    // 绑定了打印机
    // 走wifi打印机
    if (printList) {
        let info = JSON.parse(JSON.stringify(printList));
        // let hasPrinted = false; // 用于标记是否已经弹出了消息
        // let firstErrMsg = null; // 用于存储第一个错误消息
        // let requestCount = 0; // 用于计数请求的数量
        // let successCount = 0; // 用于计数成功的请求数量
        startLoading();
        let param = {
            apiUrl: info.printerServerIp,
            width: info.paperWidth,
            height: info.paperHeight,
            gap: info.paperGap,
            x: info.paperX,
            dpi: info.printerDpi,
            port: info.printerPort,
            ip: info.printerIp,
            format: info.fileFormat,
            sourceIds: ids.toString(),
            imageUrl: `https://172.30.190.70:8080/webroot/decision/view/report?viewlet=/${templateName}`,
            template: templateName,
            printModel: 'POSTEK',
            silent: true,
            printNu: '1',
            from: '2.0'
        };
        axios.post('/job/print/service?loading=true', param)
            .then(res => {
                console.log(res, 'res');
                stopLoading();
                if (res.data.code != 0) {
                    ElMessage.error(res.data.msg)
                } else {
                    ElMessage.success('打印成功');
                }
            })
            .catch(err => {
                console.log(err, 'err');
                ElMessage.error(err.data.msg)
            });
// 		for (const item of ids) {
// 			let param = {
// 				apiUrl: info.printerServerIp,
// 				width: info.paperWidth,
// 				height: info.paperHeight,
// 				gap: info.paperGap,
// 				x: info.paperX,
// 				dpi: info.printerDpi,
// 				port: info.printerPort,
// 				ip: info.printerIp,
// 				format: info.fileFormat,
// 				sourceIds: item,
// 				search: item,
// 				imageUrl: 'https://172.30.190.70:8080/webroot/decision/view/report?viewlet=/' + templateName + '&search=' + item,
// 				template: templateName,
// 				printModel: 'POSTEK',
// 				silent: true,
// 				printNu: '1',
// 				from: '2.0'
// 			};
//
//
// 			axios.post('/job/print/service?loading=true', param)
// 				.then(res => {
// 					console.log(res, 'res');
// 					requestCount++; // 请求完成，计数增加
// 					if (res.data.code == 0) {
// 						successCount++; // 成功请求，计数增加
// 					} else if (!firstErrMsg) {
// 						firstErrMsg = res.data.msg; // 记录第一个错误消息
// 					}
// 					// 检查是否所有请求都已完成
// 					if (requestCount === ids.length) {
// 						stopLoading(); // 停止 loading
// 						if (successCount === ids.length) {
// 							ElMessage.success('打印成功'); // 所有请求都成功
// 						} else if (firstErrMsg) {
// 							ElMessage.error(firstErrMsg); // 显示第一个错误消息
// 						}
// 					}
// 				})
// 				.catch(err => {
// 					console.log(err, 'err');
// 					requestCount++; // 请求完成，计数增加
// 					if (!firstErrMsg) {
// 						firstErrMsg = err.response && err.response.data && err.response.data.msg ? err.response.data.msg : '打印失败';
// 					}
// 					// 检查是否所有请求都已完成
// 					if (requestCount === ids.length) {
// 						stopLoading(); // 停止 loading
// 						if (firstErrMsg) {
// 							ElMessage.error(firstErrMsg); // 显示第一个错误消息
// 						}
// 					}
// 				});
//
//
// 		}
//
// // 如果所有请求都失败了，确保至少弹出一次错误消息
// 		if (!hasPrinted && firstErrMsg) {
// 			ElMessage.error(firstErrMsg);
// 		}

    } else {
        if (typeof window.FR !== 'undefined' && typeof window.FR.doURLPrint === 'function') {
            window.FR.doURLPrint(config);
        } else {
            console.error('FR.doURLPrint 函数未定义');
        }
    }
}


